//
//  SHKRealmManager.m
//  EagleCloud
//
//  Created by Cer on 2019/8/5.
//

#import "YsRealmToolsManager.h"

@implementation YsRealmToolsManager

+ (void)setupConfigWithDirName:(NSString *)DirName
                 withRealmName:(NSString *)realmName {
    
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [docDir stringByAppendingPathComponent:DirName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    // fileExistsAtPath 判断一个文件或目录是否有效，isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) ) {
        // 在 tmp 目录下创建一个 temp 目录
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSString *realmPath = [filePath stringByAppendingPathComponent:realmName];
    RLMRealmConfiguration * config = [RLMRealmConfiguration defaultConfiguration];
    config.schemaVersion = 44;
    config.fileURL = [NSURL URLWithString:realmPath];
    config.migrationBlock = ^(RLMMigration * _Nonnull migration, uint64_t oldSchemaVersion) {
        if (oldSchemaVersion < 44) {
            NSLog(@"进行数据迁移");
//            [migration enumerateObjects:SHKPageTable.className block:^(RLMObject * _Nullable oldObject, RLMObject * _Nullable newObject) {
//                newObject[@"pageTableID"] = oldObject[@"ys_orderiId"];
//            }];
        }else{
            NSLog(@"不进行数据迁移");
        }
    };
    [RLMRealmConfiguration setDefaultConfiguration:config];
    [RLMRealm defaultRealm];
}

+ (RLMRealm *)getRealmWithPath:(NSString *)path {
    NSString *realmPath = [[self getDocumentsPath] stringByAppendingPathComponent:@"tmpRealm/SmartPen.realm"];
    RLMRealmConfiguration * config = [RLMRealmConfiguration defaultConfiguration];
    config.fileURL = [NSURL URLWithString:realmPath];
    RLMRealm *realm = [RLMRealm realmWithConfiguration:config error:nil];
    return realm;
}

+ (BOOL)writeObj:(YsRealmToolsBaseModel *)obj {
    RLMRealm *realm = [self getRealmWithPath:@""];
    return [realm transactionWithBlock:^{
        [realm addOrUpdateObject:obj];
    } error:nil];
}

+ (BOOL)ys_writeObj:(YsRealmToolsBaseModel *)obj
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    return [realm transactionWithBlock:^{
        [realm addObject:obj];
    } error:nil];
}


+ (BOOL)writeObjs:(NSArray<YsRealmToolsBaseModel *> *)objs
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    return [realm transactionWithBlock:^{
        [realm addOrUpdateObjects:objs];
    } error:nil];
}

+ (BOOL)ys_writeObjs:(NSArray<YsRealmToolsBaseModel *> *)objs
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    return [realm transactionWithBlock:^{
        [realm addObjects:objs];
    } error:nil];
}

+ (NSArray<YsRealmToolsBaseModel *> *)queryAllObj:(Class)clazz
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    RLMResults<YsRealmToolsBaseModel *> *queryResult = [clazz allObjectsInRealm:realm];
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSInteger i = 0; i < queryResult.count; i ++) {
        YsRealmToolsBaseModel *item = [queryResult objectAtIndex:i];
        [resultArray addObject:item];
    }
    return resultArray;
}


+ (NSArray<YsRealmToolsBaseModel *> *)queryObjsWithPredicate:(NSPredicate *)predicate keyPath:(NSString *)keyPath ascending:(BOOL)ascending  targetClass:(Class)clazz
{
    RLMRealm *realm = [self getRealmWithPath:@""];

    RLMResults<YsRealmToolsBaseModel *> *queryResult = [[clazz objectsInRealm:realm withPredicate:predicate]
                                             sortedResultsUsingKeyPath:keyPath
                                             ascending:ascending];
    
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSInteger i = 0; i < queryResult.count; i ++) {
        YsRealmToolsBaseModel *item = [queryResult objectAtIndex:i];
        [resultArray addObject:item];
    }
    return resultArray;
}


+ (NSArray<YsRealmToolsBaseModel *> *)queryObjsWithPredicate:(NSPredicate *)predicate
                                          targetClass:(Class)clazz
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    
    RLMResults<YsRealmToolsBaseModel *> *queryResult = [clazz objectsInRealm:realm withPredicate:predicate];
                                        
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSInteger i = 0; i < queryResult.count; i ++) {
        YsRealmToolsBaseModel *item = [queryResult objectAtIndex:i];
        [resultArray addObject:item];
    }
    return resultArray;
}


+ (YsRealmToolsBaseModel *)queryObjWithPrimaryKey:(id)primaryKey targetClass:(Class)clazz;
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    YsRealmToolsBaseModel *queryObj = [clazz objectInRealm:realm forPrimaryKey:primaryKey];
    return queryObj;
}

+ (BOOL)deleteObj:(YsRealmToolsBaseModel *)obj
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    return [realm transactionWithBlock:^{
        [realm deleteObject:obj];
    } error:nil];
}

+ (BOOL)deleteObjs:(NSArray<YsRealmToolsBaseModel *> *)objs
{
    if (!objs) return NO;
    RLMRealm *realm = [self getRealmWithPath:@""];
    return [realm transactionWithBlock:^{
        [realm deleteObjects:objs];
    } error:nil];
}

+ (BOOL)deleteObjWithPrimaryKey:(id)primaryKey targetClass:(Class)clazz
{
    YsRealmToolsBaseModel *obj = [self queryObjWithPrimaryKey:primaryKey targetClass:clazz];
    if (obj) {
        return [self deleteObj:obj];
    } else {
        return NO;
    }
}

+ (BOOL)deleteAllTargetObjs:(Class)clazz
{
    NSArray *objs = [self queryAllObj:clazz];
    return [self deleteObjs:objs];
}

+ (BOOL)updateObj:(void (^)(void))updateBlock
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    return [realm transactionWithBlock:^{
        updateBlock();
    } error:nil];
}

+ (NSArray<YsRealmToolsBaseModel *> *)convertWithRLMArray:(RLMArray<YsRealmToolsBaseModel *> *)RLMArray
{
    NSMutableArray *resultArray = [NSMutableArray array];
    for (NSInteger i = 0; i < RLMArray.count; i ++) {
        YsRealmToolsBaseModel *item = [RLMArray objectAtIndex:i];
        [resultArray addObject:item];
    }
    return resultArray;
}

+ (BOOL)clear
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    return [realm transactionWithBlock:^{
        [realm deleteAllObjects];
    } error:nil];
}

+ (void)refresh
{
    RLMRealm *realm = [self getRealmWithPath:@""];
    [realm refresh];
}

// 获取Documents路径
+ (NSString *)getDocumentsPath {
    
    NSArray *pathArr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [pathArr firstObject];
    return path;
}
@end
